package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.dto.MaterialDto;
import org.mms.pojo.entity.Material;
import org.mms.pojo.entity.MaterialType;
import org.mms.pojo.entity.Warehouse;
import org.mms.pojo.request.MaterialRequest;
import org.mms.repository.MaterialRepository;
import org.mms.repository.MaterialTypeRepository;
import org.mms.repository.WarehouseRepository;
import org.mms.service.MaterialService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialServiceImpl implements MaterialService {
    @Autowired
    private MaterialRepository materialRepository;
    @Autowired
    private MaterialTypeRepository materialTypeRepository;
    @Autowired
    private WarehouseRepository warehouseRepository;

    @Override
    public List<Material> list() {
        return materialRepository.findAll();
    }

    @Override
    public Material getById(Long id) {
        return materialRepository.findById(id)
                .orElseThrow(() -> new BusinessException("物资不存在"));
    }

    @Override
    public Material create(MaterialRequest request) {
        Material entity = new Material();
        BeanUtils.copyProperties(request, entity);
        MaterialType materialType = materialTypeRepository.findById(request.getTypeId())
                .orElseThrow(() -> new BusinessException("物资类型不存在"));
        Warehouse warehouse = warehouseRepository.findById(request.getWarehouseId())
                .orElseThrow(() -> new BusinessException("仓库不存在"));
        entity.setMaterialType(materialType);
        entity.setWarehouse(warehouse);
        return materialRepository.save(entity);
    }

    @Override
    public Material update(MaterialRequest request) {
        Material entity = materialRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("物资不存在"));
        BeanUtils.copyProperties(request, entity);
        MaterialType materialType = materialTypeRepository.findById(request.getTypeId())
                .orElseThrow(() -> new BusinessException("物资类型不存在"));
        Warehouse warehouse = warehouseRepository.findById(request.getWarehouseId())
                .orElseThrow(() -> new BusinessException("仓库不存在"));
        entity.setMaterialType(materialType);
        entity.setMaterialType(materialType);
        entity.setWarehouse(warehouse);
        return materialRepository.save(entity);
    }

    @Override
    public void delete(Long id) {
        materialRepository.deleteById(id);
    }
}